//
//  PokerReplayerViewController.m
//  PokerReplayer
//
//  Created by 徐 庆 on 11-4-1.
//  Copyright 2011 远航游戏中心. All rights reserved.
//

#import "PokerReplayerViewController.h"


@implementation PokerReplayerViewController

@synthesize xmlHelper, xmlNodes, initPoint, elementPic;
@synthesize backGroundImage, player0Avater, player1Avater, player2Avater, firstCallLordCardImage;
@synthesize player0Name, player1Name, player2Name, firstCallLordCardText, laiZiText, gameTimesText;

/*
 // The designated initializer. Override to perform setup that is required before the view is loaded.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization
 }
 return self;
 }
 */


// Implement loadView to create a view hierarchy programmatically, without using a nib.
//这里开启视图load的事件会导致在interface builder 里设置的底图会被清掉
//- (void)loadView {
//	UIView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Images/backgroud.png"]];

//	UIImageView *contentView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
//	[contentView setImage:[UIImage imageNamed:@"backgroud.png"]];  
//	[contentView setUserInteractionEnabled:YES];  
//	self.backGroundView = contentView;  
//	[contentView release];
//	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]];
//}




// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	//[backGroundImage setImage:[UIImage imageNamed:@"Images/backgroud.png"]];
	
	self.xmlHelper = [[XMLHelper alloc] init];
	self.xmlNodes = (XMLNodes *)[xmlHelper parserXML];
	//[xmlHelper test];  
	
	[self initStaticInfo];
	
	//[self showOverInfo];
	
	int actionCount = [self.xmlNodes.m_gameInfoNode.gameActionNode count];

	//将slider每次移动的单位放大，避免float不准确问题
	playerSlider.maximumValue = (actionCount+1)*20;
	
	//NSTimer 计时不准确
	NSTimer *timer = [[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timerEvent) userInfo:nil repeats:YES] retain];
	
	
	//[xmlHelper release];
}

//初始化静态的信息如玩家头像、玩家名称、首先叫牌的玩家==
- (void)initStaticInfo{
	NSString *suit = [self.xmlNodes.m_playerInfoNode.firstCallLordCard substringToIndex:1];
	NSString *card = [self.xmlNodes.m_playerInfoNode.firstCallLordCard substringFromIndex:1];
	self.initPoint= [[InitPoint alloc] init];
	firstCallLordCardImage.frame = CGRectMake(self.initPoint.elmentPoint.firstCallLordCard.x, self.initPoint.elmentPoint.firstCallLordCard.y, firstCallLordCardImage.frame.size.width, firstCallLordCardImage.frame.size.height);
	self.elementPic = [[ElementPic alloc] init];
	//设置叫牌玩家的花色图片
	[firstCallLordCardImage setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@%@%@", elementPic.FirstCallLordCard, suit, @".png"]]];
	//设置叫牌玩家牌面
	if (card) {
		if ([card isEqualToString: @"1"]) {
			self.firstCallLordCardText.text = @"A";
		}
		else if ([card isEqualToString: @"A"]) {
			self.firstCallLordCardText.text = @"10";
		}
		else if ([card isEqualToString: @"0"]) {
			self.firstCallLordCardText.text = @"--";
		}
		else if ([card isEqualToString: @"B"]) {
			self.firstCallLordCardText.text = @"J";
		}
		else if ([card isEqualToString: @"C"]) {
			self.firstCallLordCardText.text = @"Q";
		}
		else if ([card isEqualToString: @"D"]) {
			self.firstCallLordCardText.text = @"K";
		}
		else {
			self.firstCallLordCardText.text = card;
		}
	}
	
	//初始化玩家名称
	self.player0Name.text = ((PlayerInfo *)[self.xmlNodes.m_playerInfoNode.m_playerInfo objectAtIndex:0]).userName;
	self.player1Name.text = ((PlayerInfo *)[self.xmlNodes.m_playerInfoNode.m_playerInfo objectAtIndex:1]).userName;
	self.player2Name.text = ((PlayerInfo *)[self.xmlNodes.m_playerInfoNode.m_playerInfo objectAtIndex:2]).userName;
	
	
	//初始化玩家头像
	[self.player0Avater setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@%@%@", elementPic.PicPlayer, ((PlayerInfo *)[self.xmlNodes.m_playerInfoNode.m_playerInfo objectAtIndex:0]).sex, @".png"]]];
	[self.player1Avater setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@%@%@", elementPic.PicPlayer, ((PlayerInfo *)[self.xmlNodes.m_playerInfoNode.m_playerInfo objectAtIndex:1]).sex, @".png"]]];
	[self.player2Avater setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@%@%@", elementPic.PicPlayer, ((PlayerInfo *)[self.xmlNodes.m_playerInfoNode.m_playerInfo objectAtIndex:2]).sex, @".png"]]];
}

- (void) timeTest{
	playerSlider.value += 1;
	//NSLog(@"SliderValue:%f", playerSlider.value);
	
	if (([[NSNumber numberWithFloat:playerSlider.value] intValue] % 20) == 0 && [[NSNumber numberWithFloat:playerSlider.value] intValue] < playerSlider.maximumValue -19) {
		//NSLog(@"this is %d", [[NSNumber numberWithFloat:playerSlider.value] intValue] / 20);
		int currentAction = [[NSNumber numberWithFloat:playerSlider.value] intValue] / 20;
		NSLog(@"currentAction: %d", currentAction);
		ActionNode *currentNode = [self.xmlNodes.m_gameInfoNode.gameActionNode objectAtIndex:currentAction-1];
		
		// Show laiZi
		NSString *laizi = [currentNode.laizi substringFromIndex:1];
		if (laizi) {
			if ([laizi isEqualToString: @"1"]) {
				self.laiZiText.text = @"A";
			}
			else if ([laizi isEqualToString: @"A"]) {
				self.laiZiText.text = @"10";
			}
			else if ([laizi isEqualToString: @"0"]) {
				self.laiZiText.text = @"--";
			}
			else if ([laizi isEqualToString: @"B"]) {
				self.laiZiText.text = @"J";
			}
			else if ([laizi isEqualToString: @"C"]) {
				self.laiZiText.text = @"Q";
			}
			else if ([laizi isEqualToString: @"D"]) {
				self.laiZiText.text = @"K";
			}
			else {
				self.laiZiText.text = laizi;
			}
		}
		
		// Show GameTimes
		self.gameTimesText.text = currentNode.gameTimes;
		
		
		// Show hidecard
		for (int i=0; i< [currentNode.playerHideCard.actionHideCard count]; i++) {
			NSString *PicPath = [[NSString alloc] initWithFormat:@"%@%@%@", elementPic.PicUrl_L, [currentNode.playerHideCard.actionHideCard objectAtIndex:i], @".png"];
			UIImageView * hideCardImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PicPath]];
			hideCardImage.frame = CGRectMake(self.initPoint.elmentPoint.hindCard.x+i*80, self.initPoint.elmentPoint.hindCard.y, 70.0, 95.0);
			[self.view addSubview:hideCardImage];
			[PicPath release];
			[hideCardImage release];
		}
	}
}

//心跳时触发的函数
- (void)timerEvent{
	
	//slider每次增加都移动1个单位
	playerSlider.value += 1;
	
	[self cleanGarbage:1112];	// Clean Garbage
	[self cleanGarbage:1111];	// Clean Garbage
	[self cleanGarbage:1110];	// Clean Garbage
	[self cleanGarbage:1100];	// Clean Garbage
	if (playerSlider.value == playerSlider.maximumValue) {
		
		[self showOverInfo];
	}

	if (([[NSNumber numberWithFloat:playerSlider.value] intValue] % 20) == 0 && playerSlider.value < playerSlider.maximumValue) {
		//NSLog(@"this is %d", [[NSNumber numberWithFloat:playerSlider.value] intValue] / 20);
		int currentAction = [[NSNumber numberWithFloat:playerSlider.value] intValue] / 20;
		ActionNode *currentNode = [self.xmlNodes.m_gameInfoNode.gameActionNode objectAtIndex:currentAction-1];
		
		// Show laiZi
		NSString *laizi = [currentNode.laizi substringFromIndex:1];
		if (laizi) {
			if ([laizi isEqualToString: @"1"]) {
				self.laiZiText.text = @"A";
			}
			else if ([laizi isEqualToString: @"A"]) {
				self.laiZiText.text = @"10";
			}
			else if ([laizi isEqualToString: @"0"]) {
				self.laiZiText.text = @"--";
			}
			else if ([laizi isEqualToString: @"B"]) {
				self.laiZiText.text = @"J";
			}
			else if ([laizi isEqualToString: @"C"]) {
				self.laiZiText.text = @"Q";
			}
			else if ([laizi isEqualToString: @"D"]) {
				self.laiZiText.text = @"K";
			}
			else {
				self.laiZiText.text = laizi;
			}
		}
		
		// Show GameTimes
		self.gameTimesText.text = currentNode.gameTimes;
		
		
		// Show hidecard
		for (int i=0; i< [currentNode.playerHideCard.actionHideCard count]; i++) {
			NSString *PicPath = [[NSString alloc] initWithFormat:@"%@%@%@", elementPic.PicUrl_L, [currentNode.playerHideCard.actionHideCard objectAtIndex:i], @".png"];
			UIImageView * hideCardImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PicPath]];
			hideCardImage.frame = CGRectMake(self.initPoint.elmentPoint.hindCard.x+i*80, self.initPoint.elmentPoint.hindCard.y, 70.0, 95.0);
			[self.view addSubview:hideCardImage];
			[PicPath release];
			[hideCardImage release];
		}
		
		// Show ActionNode
		for (int i=0; i<[self.xmlNodes.m_playerInfoNode.playerCount intValue]; i++) {	
			
			//Show HandCard
			[self cleanGarbage:(i+1)*100]; // Clean Garbage
			for (int j=0; j<[((PokerList *)[currentNode.playerHandCard.playerHandCardList objectAtIndex:i]).pokers count]; j++) {
				NSString *PicPath = [[NSString alloc] initWithFormat:@"%@%@%@", elementPic.PicUrl_L, [((PokerList *)[currentNode.playerHandCard.playerHandCardList objectAtIndex:i]).pokers objectAtIndex:j], @".png"];
				UIImageView * handCardImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PicPath]];
				CGPoint handCardPoint = ((PlayerPoint *)[self.initPoint.elmentPoint.playerPointList objectAtIndex:i]).playerHandCardPoint;  
				if (i==1) {
					handCardImage.frame = CGRectMake((1024-([((PokerList *)[currentNode.playerHandCard.playerHandCardList objectAtIndex:i]).pokers count]-1)*20-70)/2+j*20, handCardPoint.y, 70.0, 95.0);
				}
				else {
					handCardImage.frame = CGRectMake(handCardPoint.x, (748-([((PokerList *)[currentNode.playerHandCard.playerHandCardList objectAtIndex:i]).pokers count]-1)*20-95)/2+j*20, 70.0, 95.0);
				}
				
				handCardImage.tag = (i+1)*100;
				[self.view addSubview:handCardImage];
				
				[PicPath release];
				[handCardImage release];
			}
			
			
			// Show OutedCard
			[self cleanGarbage:(i+1)*110];	// Clean Garbage
			for (int j=0; j<[((PokerList *)[currentNode.playerOutedCard.playerOutedCardList objectAtIndex:i]).pokers count]; j++) {
				NSString *PicPath = [[NSString alloc] initWithFormat:@"%@%@%@", elementPic.PicUrl_L, [((PokerList *)[currentNode.playerOutedCard.playerOutedCardList objectAtIndex:i]).pokers objectAtIndex:j], @".png"];
				UIImageView * outedCardImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PicPath]];
				CGPoint outedCardPoint = ((PlayerPoint *)[self.initPoint.elmentPoint.playerPointList objectAtIndex:i]).playerOutedCardPoint;  
				if (i==1) {
					outedCardImage.frame = CGRectMake((1024-([((PokerList *)[currentNode.playerOutedCard.playerOutedCardList objectAtIndex:i]).pokers count]-1)*20-70)/2+j*20, outedCardPoint.y, 70.0, 95.0);
				}
				else {
					outedCardImage.frame = CGRectMake(outedCardPoint.x, (748-([((PokerList *)[currentNode.playerOutedCard.playerOutedCardList objectAtIndex:i]).pokers count]-1)*20-95)/2+j*20, 70.0, 95.0);
				}
				
				outedCardImage.tag = (i+1)*110;
				[self.view addSubview:outedCardImage];
				
				[PicPath release];
				[outedCardImage release];
			}
			
			
			// Show PlayerState
			[self cleanGarbage:(i+1)*111];	// Clean Garbage
			NSString *PicPath = [[NSString alloc] initWithFormat:@"%@%@%@", elementPic.State, ((PlayerStateInfo *)[currentNode.playerState.playerStateList objectAtIndex:i]).action_state, @".png"];
			//NSLog(@"%@", PicPath);
			UIImageView * action_stateImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PicPath]];
			CGPoint action_statePoint = ((PlayerPoint *)[self.initPoint.elmentPoint.playerPointList objectAtIndex:i]).playerState;
			action_stateImage.frame = CGRectMake(action_statePoint.x, action_statePoint.y, 63.0, 23.0);
			action_stateImage.tag = (i+1)*111;
			[self.view addSubview:action_stateImage];
			
			[PicPath release];
			[action_stateImage release];
			
			// Show remnantPoint
			[self cleanGarbage:(i+1)*1000];	// Clean Garbage
			NSString *residualCard = [[NSString alloc] initWithFormat:@"%d",[((PokerList *)[currentNode.playerHandCard.playerHandCardList objectAtIndex:i]).pokers count]];
			//NSLog(@"%d",[residualCard length]);
			for (int j=0; j<[residualCard length]; j++) {
				//NSLog(@"qewr:%@", [residualCard substringWithRange:NSMakeRange(j, 1)]);
				NSString *PicPath = [[NSString alloc] initWithFormat:@"%@%@%@", elementPic.PicNumber, [residualCard substringWithRange:NSMakeRange(j, 1)], @".png"];
				//NSLog(@"%@", PicPath);
				UIImageView * residualCardImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PicPath]];
				CGPoint residualCardPoint = ((PlayerPoint *)[self.initPoint.elmentPoint.playerPointList objectAtIndex:i]).remnantPoint;
				residualCardImage.frame = CGRectMake(residualCardPoint.x+15*j, residualCardPoint.y, 12.0, 16.0);
				residualCardImage.tag = (i+1)*1000;
				[self.view addSubview:residualCardImage];
				
				[PicPath release];
				[residualCardImage release];
			}
		}
	}
}

- (void) showOverInfo{
	NSArray *winner = [self.xmlNodes.m_gameInfoNode.gameOverInfo.winner componentsSeparatedByString:@";"];
	for (int i=0; i<[winner count]; i++) {
		int lastCount = [self.xmlNodes.m_gameInfoNode.gameActionNode count] - 1;
		ActionNode *temp = [self.xmlNodes.m_gameInfoNode.gameActionNode objectAtIndex: lastCount];
		NSString *PicPath;
		if ([[[NSString alloc] initWithFormat:@"%@", [winner objectAtIndex:i]] isEqualToString: @"1"] && [((PlayerStateInfo *)[temp.playerState.playerStateList objectAtIndex:i]).identity_state isEqualToString:@"1"]) {
			// 地主赢
			PicPath = [[NSString alloc] initWithFormat:@"%@%@", elementPic.PicOver, @"1.png"];
		}
		else {
			// 农民赢
			PicPath = [[NSString alloc] initWithFormat:@"%@%@", elementPic.PicOver, @"0.png"];
		}	
		UIImageView * gameOverImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:PicPath]];
		gameOverImage.frame = CGRectMake(self.initPoint.elmentPoint.gameOver.x, self.initPoint.elmentPoint.gameOver.y, 333.0, 215.0);
		gameOverImage.tag = 1100;
		[self.view addSubview:gameOverImage];
		[PicPath release];
		[gameOverImage release];
	}
	UIFont *font = [UIFont systemFontOfSize:13.0];
	UILabel *overLeftInfo = [[UILabel alloc] init];
	overLeftInfo.frame = CGRectMake(self.initPoint.elmentPoint.gameOver.x+13, self.initPoint.elmentPoint.gameOver.y+40, 200.0, 180.0);
	overLeftInfo.lineBreakMode = UILineBreakModeWordWrap;
	overLeftInfo.numberOfLines = 0;
	[overLeftInfo setFont:font]; //设置字体
	[overLeftInfo setBackgroundColor:[UIColor clearColor]]; //设置背景色
	[overLeftInfo setTextColor:[UIColor greenColor]];
	overLeftInfo.text = [[NSString alloc] initWithFormat:@"%@%@%@%@%@%@%@%@%@", self.xmlNodes.m_gameInfoNode.gameOverInfo.gameSumTimes, @"\n", self.xmlNodes.m_gameInfoNode.gameOverInfo.grabLordTimes, @"\n", self.xmlNodes.m_gameInfoNode.gameOverInfo.bombTimes, @"\n", self.xmlNodes.m_gameInfoNode.gameOverInfo.mingCard, @"\n", self.xmlNodes.m_gameInfoNode.gameOverInfo.mingCardBegin];
	overLeftInfo.tag = 1110;
	[self.view addSubview:overLeftInfo];
	[overLeftInfo release];
	
	UILabel *overUserName = [[UILabel alloc] init];
	overUserName.frame = CGRectMake(self.initPoint.elmentPoint.gameOver.x+120, self.initPoint.elmentPoint.gameOver.y+80, 200.0, 140.0);
	overUserName.lineBreakMode = UILineBreakModeWordWrap;
	overUserName.numberOfLines = 0;
	[overUserName setFont:font]; //设置字体
	[overUserName setBackgroundColor:[UIColor clearColor]]; //设置背景色
	[overUserName setTextColor:[UIColor greenColor]];
	NSMutableString *nameText = [[NSMutableString alloc] init];
	for (int i=0; i<[self.xmlNodes.m_playerInfoNode.playerCount intValue]; i++) {
		[nameText appendString:((PlayerInfo *)[self.xmlNodes.m_playerInfoNode.m_playerInfo objectAtIndex:i]).userName];
		[nameText appendString:@"\n\n"];
	}
	overUserName.text = nameText;
	overUserName.tag = 1111;
	[self.view addSubview:overUserName];
	[nameText release];
	[overUserName release];
	
	
	
	UILabel *overRightInfo = [[UILabel alloc] init];
	overRightInfo.frame = CGRectMake(self.initPoint.elmentPoint.gameOver.x+245, self.initPoint.elmentPoint.gameOver.y+80, 200.0, 140.0);
	overRightInfo.lineBreakMode = UILineBreakModeWordWrap;
	overRightInfo.numberOfLines = 0;
	[overRightInfo setFont:font]; //设置字体
	[overRightInfo setBackgroundColor:[UIColor clearColor]]; //设置背景色
	[overRightInfo setTextColor:[UIColor greenColor]];
	NSMutableString *rightText = [[NSMutableString alloc] init];
	for (int i=0; i<[self.xmlNodes.m_playerInfoNode.playerCount intValue]; i++) {
		if ([[[self.xmlNodes.m_gameInfoNode.gameOverInfo.winner componentsSeparatedByString:@";"] objectAtIndex:i] isEqualToString: @"1"]) {
			[rightText appendString:@"胜         "];
		}
		else {
			[rightText appendString:@"负         "];
		}

		
		[rightText appendString:[[xmlNodes.m_gameInfoNode.gameOverInfo.changePoint componentsSeparatedByString:@";"] objectAtIndex:i]];
		[rightText appendString:@"\n\n"];
	}
	overRightInfo.text = rightText;
	overRightInfo.tag = 1112;
	[self.view addSubview:overRightInfo];
	[overRightInfo release];
	[rightText release];
}

//垃圾回收(将要回收的垃圾标记上当时节点的ActionID)
- (void)cleanGarbage:(NSInteger)tag{
	for (UIView *sub in [self.view subviews]){
		if (sub.tag == tag) {
			[sub removeFromSuperview];
		}
	}
}

//展示牌相关的东西
- (void) showCard:(ActionNode *) currentNode{
	
}

//当slider值改变时触发(当手工拖动的时候才触发)
- (IBAction) sliderChange{
	NSLog(@"slidervalue: %f", playerSlider.value);
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    //return YES; 4向显示
	//横向显示
	return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

@end
